/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.yapmadanolme.dao;

import java.sql.*;
import java.io.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

import com.yapmadanolme.model.Comment;
import java.util.ArrayList;
/**
 *
 * @author Mehmet
 */
public class CommentsDao extends HttpServlet
{
     Connection connection;

     @Override
     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     {
        int command = Integer.parseInt(request.getParameter("type"));
        HttpSession session = request.getSession();
        PrintWriter out=response.getWriter();
        int authorId,wishId,commentId;
        String comment;
        switch(command)
        {
            case 1: //add comment
                comment = request.getParameter("comment");
                authorId= Integer.parseInt(request.getParameter("authorId"));
                wishId=Integer.parseInt(request.getParameter("wishId"));
                commentId=insertComment(comment,authorId,wishId);
                out.println(commentId);
                break;
            case 2: //update comment
                commentId= Integer.parseInt(request.getParameter("commentId"));
                comment = request.getParameter("comment");
                updateComment(comment, commentId);
                break;
            case 3:// get comments for a wish
                wishId= Integer.parseInt(request.getParameter("wishId"));
                List<Comment> wishList=selectComments(wishId);
                /*either use JSON or XML*/
                out.println(wishList.size());
                break;
        }
     }
    public void openConnection()// opens Database connection
    {
        String dbUrl = "jdbc:mysql://localhost:3306/yapmadanolmedb";
        String username = "root";
        String password ="1";

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(dbUrl, username,password);

        } //end try
        catch(ClassNotFoundException e) { e.printStackTrace();   }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
    public void closeConnection()//closes database connection
    {
        try {
            connection.close();
        } catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private List<Comment> selectComments(int wishId) // returns comment list of given wish
    {
        List<Comment> commentList=new ArrayList<Comment>();
        String query="select * from comments where wishID=?";
        openConnection();
        try {
            PreparedStatement stmt=connection.prepareStatement(query);
            stmt.setInt(1, wishId);
            ResultSet rs=stmt.executeQuery();
            while(rs.next())
            {
                Comment newComment= new Comment();
                newComment.setAuthorId(rs.getInt("authorID"));
                newComment.setWishId(rs.getInt("wishID"));
                newComment.setCommentId(rs.getInt("commentID"));
                newComment.setCommentText(rs.getString("commentText"));
                newComment.setDateEntered(rs.getTimestamp("dateEntered"));
                commentList.add(newComment);
            }
            rs.close();
            stmt.close();
            return commentList;
        } catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

     private int insertComment(String comment,int authorId,int wishId) //insert a new comment to a wish
     {
         int commentId=0;
         String query="insert into comments (authorID, wishID commentText) Values (?,?,?)";
         openConnection();
         try {
            PreparedStatement stmt=connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
            stmt.setInt(1, authorId);
            stmt.setInt(2,wishId);
            stmt.setString(3,comment);
            stmt.executeUpdate();
            ResultSet rs=stmt.getGeneratedKeys();
            if(rs.next())
                commentId=rs.getInt(1);
            rs.close();
            stmt.close();
        }
         catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        closeConnection();
        return commentId;
     }

     private void updateComment(String comment, int commentId) //update a comment
     {
         String query="update comments set comments.commentText=? where commentID=?";
         openConnection();
         try {
            PreparedStatement stmt=connection.prepareStatement(query);
            stmt.setString(1, comment);
            stmt.setInt(2, commentId);
            stmt.executeUpdate();
            stmt.close();
        }
         catch (SQLException ex) {
            Logger.getLogger(UsersDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        closeConnection();
     }

}
